package com.fubowen.lepton.ui.reader

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.fubowen.lepton.bean.BookBean
import com.fubowen.lepton.bean.BookChapterBean
import com.fubowen.lepton.databinding.FragmentReaderBookshelfBinding
import com.fubowen.lepton.databinding.FragmentReaderBookshelfItemBinding
import com.fubowen.lepton.helper.DBHelper
import com.fubowen.lepton.ui.base.ThemeFragment
import com.fubowen.reader.book.impl.WebBook
import com.fubowen.lepton.ui.reader.recycler.Book
import com.fubowen.lepton.ui.reader.recycler.BookshelfAdapter
import com.fubowen.reader.ui.BookshelfFragmentDirections
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class BookshelfFragment : ThemeFragment() {

    private lateinit var binding: FragmentReaderBookshelfBinding
    private lateinit var controller: NavController
    private lateinit var recycler: RecyclerView
    private lateinit var adapter: BookshelfAdapter
    private lateinit var layoutManager: LinearLayoutManager
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentReaderBookshelfBinding.inflate(inflater, container, false)
        controller = findNavController()
        initRecyclerView()
        readWebBook()
        
        binding.bookshelfHistory.setOnClickListener { 
//            val action = BookshelfFragmentDirections.actionBookshelfFragmentToViewPagerFragment()
//            findNavController().navigate(action)
        }
        return binding.root
    }

    //region initRecyclerView
    private fun initRecyclerView() {
        recycler = binding.bookshelfRecycler
        layoutManager = LinearLayoutManager(requireContext())
        adapter = BookshelfAdapter()
        recycler.layoutManager = layoutManager
        recycler.adapter = adapter
        CoroutineScope(Dispatchers.IO).launch {
            DBHelper.db.bookDao().allFlow().collect {
                adapter.submitList(it)
            }
        }
        adapter.setOnClickListener(object : BookshelfAdapter.OnClickListener {
            override fun onItemClick(view: FragmentReaderBookshelfItemBinding) {
                val position = layoutManager.getPosition(view.root)
                val item = adapter.currentList[position]
                val book = item.book
                if (book != null) {
                    openBook(book)
                }
            }
        })
    }
    //endregion

    //region goBack
    private fun goBack() {
        val onBackCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                goBackImpl()
                isEnabled = false
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(
            viewLifecycleOwner,
            onBackCallback
        )
    }

    private fun goBackImpl() {

    }
    //endregion

    //region openBook
    private fun openBook(book: Book) {
//        val action = BookshelfFragmentDirections.actionBookshelfFragmentToReaderFragment2(book.id)
//        controller.navigate(action)
    }
    //endregion

    //region 加载一本网络书籍或者本地书籍
    private fun readWebBook() {
        val url = "https://www.qishuta.org/du/7/7310/9965631.html"
        CoroutineScope(Dispatchers.IO).launch {
            val book = DBHelper.db.bookDao().getByAbsolutePath(url)
            if (book != null) {
                DBHelper.db.bookDao().changeReadingBook(book.id)
                return@launch
            }
            WebBook(url).apply {
                onCompleted = {
                    if (isGetCatalogState) {
                        val book = BookBean(
                            name = name,
                            isReading = true,
                            absolutePath = url,
                            chapterCount = chapterList.size,
                            type = BookBean.TYPE_LOCAL
                        )
                        val bookId = DBHelper.db.bookDao().set(book)
                        val chapterList = chapterList.map {
                            BookChapterBean(
                                name = it.name,
                                order = it.order,
                                url = it.url,
                                bookId = bookId.toInt(),
                                isDownload = false
                            )
                        }
                        DBHelper.db.bookDao().setOrIgnoreChapter(chapterList)
                    }
                }
                tryGet()
            }
        }
    }
    //endregion
}